/**
 * 1. 这里学到了：export default 后面不能直接跟const，而是要定义一个变量；function 定义函数，export default function
 * 
 */
import type { JSX } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { Navigate, useLocation } from 'react-router-dom';
import { Spin } from 'antd';

interface AuthRouteProps {
  children: JSX.Element;
}

// 为组件加上权限判定
const AuthRoute = ({ children }: AuthRouteProps): JSX.Element =>  {
  const { isAuthenticated, authChecked } = useAuth();
  const location = useLocation();

  // 如果认证检查尚未完成，显示加载状态
  if (!authChecked) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!isAuthenticated) {
    // 保存当前路径以便登录后重定向
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

export default AuthRoute;